<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/mail/Mailer.class.php, $Author:  $ */

if (!file_exists(App::getParam('path') . 'include/classes/pear/Mail.php'))
{
	require_once 'mime.class.php';
}

class mail_Mailer extends Object
{
    /**
     * Mailer
     *
     * @var Mail_Mime
     */
    var $oSender;
    
    var $bPearMail = false;
    
    var $oPearMail = null;

    function mail_Mailer()
    {
        parent::Object();
        
       	$sPearMail = App::getParam('path') . 'include/classes/pear/Mail.php';
        if (App::getParam('mail_type') == 'smtp' && file_exists($sPearMail))
        {
        	if (!defined('PHPFOX_PEAR_DIR'))
        	{
        		define('PHPFOX_PEAR_DIR', App::getParam('path') . 'include/classes/pear/');
        	}
        	
        	require_once $sPearMail;
        	$this->bPearMail = true;
			$this->oPearMail = Mail::factory
			(
				'smtp',
				array
				(
					'host' => App::getParam('smtp_host'),
					'auth' => (App::getParam('smtp_auth') ? true : false),
					'username' => App::getParam('smtp_user'),
					'password' => App::getParam('smtp_pass'),
					'localhost' => App::getParam('smtp_helo')
				)
			);      
 	
        	return;
        }   
        
        $this->oSender = & new Mail_Mime();
        $this->oSender->setReturnPath(App::getParam('mail_return_path'));
        $this->oSender->images_dir  = App::getParam('mail_images_dir');
		if(App::getParam('smtp_host'))
			$this->oSender->smtp_params['host'] = App::getParam('smtp_host');
		if(App::getParam('smtp_port'))
			$this->oSender->smtp_params['port'] = App::getParam('smtp_port');
		if(App::getParam('smtp_helo'))
			$this->oSender->smtp_params['helo'] = App::getParam('smtp_helo');
		if(App::getParam('smtp_auth'))
			$this->oSender->smtp_params['auth'] = App::getParam('smtp_auth');
		if(App::getParam('smtp_user'))
			$this->oSender->smtp_params['user'] = App::getParam('smtp_user');
		if(App::getParam('smtp_pass'))
			$this->oSender->smtp_params['pass'] = App::getParam('smtp_pass');
		if(App::getParam('smtp_timeout'))
			$this->oSender->smtp_params['timeout'] = App::getParam('smtp_timeout');
    }

    function get($aConf=array())
    {
		return;
    }

    function send($sTplCode, $sEmail, $sSubj, $aVars=array())
    {
        ini_set('sendmail_from', App::getSetting('site_email'));

        $sUserName = (isset($aVars['FROM']) ? $aVars['FROM'] : '');
        $aVars['SITENAME'] = App::getSetting('site_name');

		$oDb =& Database::get();       
		$oLang = &App::getLanguage();
		$iLangId = $oDb->getField("SELECT lang_file FROM " . App::getT('user') . " WHERE email = '" . $oDb->escape($sEmail) . "'");
        $srcHtml = $oLang->getContent($sTplCode, false, $iLangId);
        
	    if ($iLangId && ($oLang->aLanguage['id'] != $iLangId))
	    {
	    	$aRow = $oDb->getRow("
	    		SELECT t.text 
	    		FROM " . App::getT('language_phrase') . " AS l 
	    			LEFT JOIN " . App::getT('language_phrase') . " AS t ON(t.varname = l.varname AND t.languageid = '" . $iLangId . "')
	    		WHERE l.text = '" . $oDb->escape(trim($sSubj)) . "' AND l.languageid = '" . $oLang->aLanguage['id'] . "'
	    	");
	    	$sSubj = (isset($aRow['text']) ? $aRow['text'] : $sSubj);
	    }        

        $aTpl = array(
        	'm_subject' => $this->_compile($sSubj, $aVars),
	        'm_text'    => $this->_compile($srcHtml, $aVars),
    	    'm_html'    => $this->_compile($srcHtml, $aVars),
        );

	    $sText = $aTpl['m_text'];
	    $aTpl['m_subject'] = $this->_safe($aTpl['m_subject']);
	    
	    if (!$this->bPearMail)
	    {
        	$this->oSender->setSubject($aTpl['m_subject']);
	    }
	    
        if (App::getSetting('send_html_emails'))
        {
            $aTpl['m_html'] = str_replace("\r\n", '<br />', $aTpl['m_html']);
            $aTpl['m_html'] = str_replace("\n", '<br />', $aTpl['m_html']);
            $aVars = array
            (
                'MAINCONTENT' => $aTpl['m_html'],
                'SITENAME'    => App::getSetting('site_name'),
                'COPYRIGHT'   => App::getSetting('site_name'),
                'IMG' => '',
            );
            $srcLayout = $oLang->getContent("email_layout");
            $sHtml = $this->_compile($srcLayout, $aVars);
			
            if (!$this->bPearMail)
	    	{
        	    $this->oSender->setHtml($sHtml, $sText);
	    	}
        }
        else
        {
			$sText = preg_replace("/\<a href=\"(.*?)\"\>(.*?)\<\/a\>/i", "\\1", $sText);
			$sText = str_replace(array("<br />", "<br>"), "\n", $sText);
			$sText = strip_tags($sText);      

			if (!$this->bPearMail)
	    	{ 	
        		$this->oSender->setText($sText);
	    	}
        }

        if (!$this->bPearMail)
	    {
        	if (isset($aVars['HEADER_FROM_USER']) && isset($aVars['HEADER_FROM_EMAIL']))
        	{
        		$this->oSender->setHeader('From', $this->_safe($aVars['HEADER_FROM_USER']) . ' <' . $this->_safe($aVars['HEADER_FROM_EMAIL']) . '>');
        	}
        	else 
        	{
        		$this->oSender->setHeader('From', App::getSetting('site_name').' <'.App::getSetting('site_email').'>');
        	}
	    }

        if ( App::getParam('debug.email') )
		{
        	print (isset($sHtml) ? $sHtml : $sText);
        	exit;
        }
        
        if ($this->bPearMail)
        {        
			$aHeaders = array
			(
				'From' => '' . App::getSetting('site_name') . ' <' . App::getSetting('mail_return_path') . '>',
				'To' => '' . $sEmail . ' <' . $sEmail . '>',
				'Subject' => $aTpl['m_subject'],
				'Content-Type: text/html; charset=ISO-8859-1',
				'MIME-Version: 1.0'
			);
			
			if (App::getSetting('send_html_emails'))
			{
				$this->oMime->setTXTBody($sText);
				$this->oMime->setHTMLBody($sHtml);
				$sHtml = $this->oMime->get();
				$this->oMime->setFrom('' . App::getSetting('site_name') . ' <' . App::getSetting('mail_return_path') . '>');
				$this->oMime->setSubject($aTpl['m_subject']);
				$aHeaders = $this->oMime->headers();
			}			
			
			$oMail = $this->oPearMail->send($sEmail, $aHeaders, (isset($sHtml) ? $sHtml : $sText));
			
			if (PEAR::isError($oMail)) 
			{
				return $oMail->getMessage();
			} 
			return true;
        }
        else 
        {
        	if (!$this->oSender->send(array($sEmail)))        
        	{
        		if ( App::getParam('debug') && App::getParam('mail_type') == 'smtp' )
        		{
        			return $this->oSender->errors;
        		}
        		if ( App::getParam('debug') && App::getParam('mail_type') == 'mail' )
        		{
        			return "Email has not been sent. Attempt to use SMTP instead of SendMail.";
        		}
        	}
        }

        return true;
    }

    function _compile($sStr, $aVars)
    {
        foreach( $aVars as $k => $v)
        {
          $sStr = str_replace('<%'.strtoupper($k).'%>',$v, $sStr);
        }
        return $sStr;
    }
    
	function _safe($name) 
	{
   		return(preg_replace(array("/\r/i", "/\n/i", "/%0a/i", "/%0d/i", "/Content-Type:/i", "/bcc:/i","/to:/i","/cc:/i" ), "", $name ) );
	}    
}

?>